import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 寻找每一个人是哪些人的共同好友
 * Input:
 * 500, 100 300
 * 600, 100
 * Output:
 * 100 500,600
 * 300 500,
 */

public class SameFriend {
    public static class SameFriendMapper
            extends Mapper<Object, Text, Text, Text> {
        Text KeyOut = new Text();
        Text ValueOut = new Text();

        @Override
        protected void map(Object key, Text value, Context context)
                throws IOException, InterruptedException {
            String[] PersonFriends = value.toString().replaceAll(",", "").split(" ");
            ValueOut.set(PersonFriends[0]);
            for (int i = 1; i < PersonFriends.length; i++) {
                KeyOut.set(PersonFriends[i]);
                context.write(KeyOut, ValueOut);
            }
        }
    }

    public static class SameFriendReducer
            extends Reducer<Text, Text, Text, Text> {
        Text KeyOut = new Text();
        Text ValueOut = new Text();

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            StringBuilder Persons = new StringBuilder();
            for (Text value : values) {
                Persons.append(value.toString()).append(",");
            }
            KeyOut.set(key);
            ValueOut.set(Persons.toString());
            context.write(KeyOut, ValueOut);
        }
    }

    @SuppressWarnings("deprecation")
    public static boolean run(String in, String out)
            throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf, "SameFriend");
        job.setJarByClass(SameFriend.class);
        job.setMapperClass(SameFriendMapper.class);
        job.setReducerClass(SameFriendReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(in));
        FileOutputFormat.setOutputPath(job, new Path(out));

        return job.waitForCompletion(true);
    }
}
